package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.common.ParamPage;
import com.itheima.dao.CategoryDao;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryDao categoryDao;
    @Override
    public Page<Category> findPage(ParamPage page) {
        Page<Category> page1 = new Page<>(page.getPage(), page.getPageSize());
        categoryDao.selectPage(page1,null);
        return page1;
    }

    @Override
    public int add(Category category) {
        return categoryDao.insert(category);
    }

    @Override
    public int update(Category category) {
        return categoryDao.updateById(category);
    }

    @Override
    public int delete(Long id) {
        if (dishService.findByCid(id,null)!=null&&dishService.findByCid(id,null).size()>0){
            return -1;
        }
        if (setmealService.findByCid(id,null)!=null&&setmealService.findByCid(id,null).size()>0){
            return -2;
        }
        return categoryDao.deleteById(id);
    }

    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type!=null,Category::getType, type);
        return categoryDao.selectList(lqw);
    }

    @Override
    public Category findByCid(long id) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Category::getId,id);
        return categoryDao.selectOne(lqw);
    }
}
